import Util from "./util";
let utils = {
  template: {
    induction: 1,
  },

  /**
   * 时间戳转换，当天返回 hh:mm，一天以前返回 n天前
   * @param timestamp
   * @returns {string}
   */
  toChatFormatTimeDiff: function (timestamp) {
    // 获取时间戳对应的日期时间，格式 yyyy-MM-dd hh:mm:ss
    var lasttime = this.timestampToFormatDatetime(timestamp);
    // 获取当前系统日期时间，格式 yyyy-MM-dd hh:mm:ss
    var curtime = this.getCurDatetime();

    var lastDate = new Date(lasttime.substr(0, 4), lasttime.substr(5, 2) - 1,
      lasttime.substr(8, 2), lasttime.substr(11, 2), lasttime.substr(14, 2),
      lasttime.substr(17, 2));
    var curDate = new Date(curtime.substr(0, 4), curtime.substr(5, 2) - 1,
      curtime.substr(8, 2), curtime.substr(11, 2), curtime.substr(14, 2),
      curtime.substr(17, 2));

    var dateDifference = curDate.getTime() - lastDate.getTime();//时间差的毫秒数
    var days = Math.floor(dateDifference / (24 * 3600 * 1000))//计算出相差天数
    //计算出小时数
    var leave1 = dateDifference % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000));
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000));
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000);
    var retDate = days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";

    if (days > 0) {
      retDate = days + '天前'
    } else {
      retDate = lasttime.substr(11, 5);
    }
    return retDate;
  },
  /**
   * 时间戳转换为 yyyy-MM-dd hh:mm:ss
   * @param timestamp
   * @returns {string}
   */
  timestampToFormatDatetime: function (timestamp) {
    var end = new Date(timestamp);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var endhours = this.fix(end.getHours(), 2);
    var endminutes = this.fix(end.getMinutes(), 2);
    var endseconds = this.fix(end.getSeconds(), 2);
    var curtime = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':'
      + endminutes + ':' + endseconds;
    return curtime;
  },
  // 获取当前时间的下一个整点小时: hh:mm
  getNextHH: function () {
    var date = new Date();
    var starthours = this.fix(date.getHours(), 2);
    var endhours = '';
    if (endhours < 23) {
      starthours = this.fix(parseInt(starthours) + 1, 2);
      endhours = this.fix(parseInt(starthours) + 1, 2);
      if (endhours == 24) {
        endhours = '00';
      }
    } else {
      starthours = '08';
      endhours = '09';
    }
    var startTime = starthours + ':00';
    var endTime = endhours + ':00';
    var obj = {
      startTime: startTime,
      endTime: endTime,
    };
    return obj;
  },
  /**
   * 时间转换为 yyyy-MM-dd
   * @param date
   * @returns {string}
   */
  dateToDate: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var curtime = endyear + '-' + endmonth + '-' + endday;
    return curtime;
  },
  /**
   * 时间转换为 yyyy/MM/dd
   * @param date
   * @returns {string}
   */
  dateToDate2: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var curtime = endyear + '/' + endmonth + '/' + endday;
    return curtime;
  },
  /**
   * 时间转换为 yyyy-MM
   * @param date
   * @returns {string}
   */
  dateToMonth: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var curtime = endyear + '-' + endmonth;
    return curtime;
  },
  /**
   * 时间转换为 yyyy年MM月dd日
   * @param date
   * @returns {string}
   */
  dateToDateString: function (date) {
    var end = new Date(date);
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var curtime = endyear + '年' + endmonth + '月' + endday + '日';
    return curtime;
  },
  /**
   * 时间转换为 HH:mm
   * @param date
   * @returns {string}
   */
  dateToTime: function (date) {
    var end = new Date(date);
    var endhours = this.fix(end.getHours(), 2);
    var endminutes = this.fix(end.getMinutes(), 2);
    var curtime = endhours + ':' + endminutes;
    return curtime;
  },
  /**
   * 秒转换为时间
   * @param times
   * @returns {string}
   */
  timesToTime: function (times) {
    var curtime = '';
    if (times >= 0 && times < 60) {
      curtime = times + '秒';
    } else if (times >= 60 && times < (60 * 60)) {
      var mm = parseInt(times / 60);
      var ss = times % 60;
      curtime = mm + '分' + ss + '秒';
    } else if (times >= (60 * 60) && times < (60 * 60 * 24)) {
      var hh = parseInt(times / (60 * 60));
      var mm = parseInt(times % (60 * 60) / 60);
      var ss = times % (60 * 60) % 60;
      curtime = hh + '小时' + mm + '分' + ss + '秒';
    } else if (times >= (60 * 60 * 24)) {
      var dd = parseInt(times / (60 * 60 * 24));
      var hh = parseInt((times % (60 * 60 * 24)) / (60 * 60));
      var mm = parseInt((times % (60 * 60 * 24)) % (60 * 60) / 60);
      var ss = ((times % (60 * 60 * 24)) % (60 * 60)) % 60;
      curtime = dd + '天' + hh + '小时' + mm + '分' + ss + '秒';
    }
    return curtime;
  },
  /**
   * 分转换为时间
   * @param times
   * @returns {string}
   */
  minutesToTime: function (times) {
    var curtime = '';
    times = parseInt(times) * 60;
    if (times >= 0 && times < 60) {
      curtime = times + ' 秒';
    } else if (times >= 60 && times < (60 * 60)) {
      var mm = parseInt(times / 60);
      var ss = times % 60;
      curtime = mm + ' 分 ' + ss + ' 秒';
    } else if (times >= (60 * 60) && times < (60 * 60 * 24)) {
      var hh = parseInt(times / (60 * 60));
      var mm = parseInt(times % (60 * 60) / 60);
      var ss = times % (60 * 60) % 60;
      curtime = hh + ' 小时 ' + mm + ' 分 ' + ss + ' 秒';
    } else if (times >= (60 * 60 * 24)) {
      var dd = parseInt(times / (60 * 60 * 24));
      var hh = parseInt((times % (60 * 60 * 24)) / (60 * 60));
      var mm = parseInt((times % (60 * 60 * 24)) % (60 * 60) / 60);
      var ss = ((times % (60 * 60 * 24)) % (60 * 60)) % 60;
      curtime = dd + ' 天 ' + hh + ' 小时 ' + mm + ' 分 ' + ss + ' 秒';
    }
    return curtime;
  },
  /**
   * 分转换为时间,超过 24 小时是 1 天，超过 30 天是 1 月，超过 12 月是 1 年
   * @param times
   * @returns {string}
   */
  minutesToTime1: function (times) {
    var curtime = '';
    times = parseInt(times) * 60;
    if (times >= 0 && times < 60) {

    } else if (times >= 60 && times < (60 * 60)) {
      var mm = parseInt(times / 60);
      var ss = times % 60;
      curtime = mm + ' 分';
    } else if (times >= (60 * 60) && times < (60 * 60 * 24)) {
      var hh = parseInt(times / (60 * 60));
      var mm = parseInt(times % (60 * 60) / 60);
      curtime = hh + ' 小时 ' + mm + ' 分';
    } else if (times >= (60 * 60 * 24) && times < (60 * 60 * 24 * 30)) {
      var dd = parseInt(times / (60 * 60 * 24));
      var hh = parseInt((times % (60 * 60 * 24)) / (60 * 60));
      var mm = parseInt((times % (60 * 60 * 24)) % (60 * 60) / 60);
      curtime = dd + ' 天 ' + hh + ' 小时 ' + mm + ' 分';
    } else if (times >= (60 * 60 * 24 * 30)) {
      var MM = parseInt(times / (60 * 60 * 24 * 30));
      var dd = parseInt((times % (60 * 60 * 24 * 30)) / (60 * 60 * 24));
      var hh = parseInt(((times % (60 * 60 * 24 * 30)) % (60 * 60 * 24)) / (60 * 60));
      var mm = parseInt((((times % (60 * 60 * 24 * 30)) % (60 * 60 * 24) % (60 * 60)) / 60));
      if (MM < 12) {
        curtime = MM + ' 月 ' + dd + ' 天 ' + hh + ' 小时 ' + mm + ' 分';
      } else {
        var yy = parseInt(MM / 12);
        MM = parseInt(MM % 12);
        curtime = yy + ' 年 ' + MM + ' 月 ' + dd + ' 天 ' + hh + ' 小时 ' + mm + ' 分';
      }
    }
    return curtime;
  },
  /**
   * 分转换为时间
   * @param times
   * @returns {string}
   */
  minutesToTime2: function (times) {
    var curtime = '';
    times = parseInt(times);
    if (times >= 0 && times < 60) { // 0-1小时
      curtime = times + ' 分';
    } else if (times >= 60 && times < 60 * 24) { // 1小时-1天
      var hh = parseInt(times / (60));
      var mm = parseInt(times % (60));
      curtime = hh + ' 小时 ' + mm + ' 分';
    } else if (times >= 60 * 24 && times < 60 * 24 * 3) { // 1天-3天
      var dd = parseInt(times / (60 * 24));
      var hh = parseInt((times % (60 * 24)) / (60 ));
      curtime = dd + ' 天 ' + hh + ' 小时';
    } else if (times >= 60 * 24 * 3 && times < 60 * 24 * 7) { // 3天-7天
      var dd = parseInt(times / (60 * 24));
      curtime = dd + ' 天';
    } else if (times >= 60 * 24 * 7 && times < 60 * 24 * 30) { // 7天-30天
      var ww = parseInt(times / (60 * 24 * 7));
      curtime = ww + ' 周';
    } else if (times >= 60 * 24 * 30 && times < 60 * 24 * 30 * 12) { // 30天-12月
      var MM = parseInt(times / (60 * 24 * 30));
      curtime = MM + ' 月';
    } else if (times >= 60 * 24 * 30 * 12) { // 12月~
      var yy = parseInt(times / (60 * 24 * 30 * 12));
      curtime = yy + ' 年';
    }
    return curtime;
  },
  /**
   * 设置数字几位数显示；例console.log(fix(5, 2));输出结果为05
   * @param num
   * @param length
   * @returns {string}
   */
  fix: function (num, length) {
    return ('' + num).length < length ? ((new Array(length + 1)).join('0')
    + num).slice(-length) : '' + num;
  },
  /**
   * 获取当前系统时间并按照一定格式返回
   * @returns {string} format{yyyy-MM-dd HH:mm:ss}
   */
  getCurDatetime: function () {
    var end = new Date();
    var endyear = this.fix(end.getFullYear(), 4);
    var endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    var endday = this.fix(end.getDate(), 2);
    var endhours = this.fix(end.getHours(), 2);
    var endminutes = this.fix(end.getMinutes(), 2);
    var endseconds = this.fix(end.getSeconds(), 2);
    var curtime = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':'
      + endminutes + ':' + endseconds;
    return curtime;
  },
  computeFileSize: function (size) {
    size = (size / 1024).toFixed(2);//K
    if (size > 1024) {
      size = (size / 1024).toFixed(2);//M
      size = size + 'M';
    } else {
      size = size + 'K';
    }
    return size;
  },
  convertImgToDataURLviaCanvas: function (url, callback, outputFormat) {
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
      var canvas = document.createElement('CANVAS');
      var ctx = canvas.getContext('2d');
      var dataURL;
      canvas.height = this.height;
      canvas.width = this.width;
      ctx.drawImage(this, 0, 0);
      dataURL = canvas.toDataURL(outputFormat);
      //dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
      callback(dataURL);
      canvas = null;
    };
    img.src = url;
  },
  checkNumber: function (number) {
    //正则：验证数字 大于0
    var reg = /^\+?[1-9][0-9]*$/;
    if (!reg.test(number)) {
      return false;
    }
    else {
      return true;
    }
  },
  checkMobile: function (phone) {
    //正则：验证电话号码手机号码，包含至今所有号段
    var reg = /^(1[3|4|5|7|8])[\d]{9}$/;
    if (!reg.test(phone)) {//alert("电话号码格式错误!");obj.value="";obj.focus();
      return false
    }
    else {//alert("您的电话号码:"+phone);
      return true
    }
  },
  UrlEncode: function (str) {
    function str2asc(strstr) {
      return ("0" + strstr.charCodeAt(0).toString(16)).slice(-2)
    }

    function asc2str(ascasc) {
      return String.fromCharCode(ascasc)
    }

    var ret = "";
    var strSpecial = "!\"#$%&'()*+,/:;<=>?[]^`{|}~%";
    var tt = "";

    for (var i = 0; i < str.length; i++) {
      var chr = str.charAt(i);
      var c = str2asc(chr);
      tt += chr + ":" + c + "n"
      if (parseInt("0x" + c) > 0x7f) {
        ret += "%" + c.slice(0, 2) + "%" + c.slice(-2)
      } else {
        if (chr == " ")
          ret += "+"
        else if (strSpecial.indexOf(chr) != -1)
          ret += "%" + c.toString(16)
        else
          ret += chr
      }
    }
    return ret
  },
  toStr: function (obj) {
    var res = '';
    if (typeof obj == 'string') {
      res = obj
    } else if (typeof obj == 'object') {
      res = JSON.stringify(obj)
    }
    return res
  },
  toJson: function (str) {
    var res = ''
    if (str != '' && str != undefined && str != null) {
      if (typeof str == 'string') {
        str = str.trim()
        res = JSON.parse(str) ? JSON.parse(str) : eval('(' + str + ')')
      } else if (typeof str == 'object') {
        res = str
      }
    }
    return res
  },
  //生成从minNum到maxNum的随机数
  getRandomNum: function (minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        break;
      default:
        return 0;
        break;
    }
  },
  /**
   * 设置固定过期时间的cookies
   */
  setCookie: function (name, value, Days) {
    /*var Days = Days ? Days : 30
     var exp = new Date()
     exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
     document.cookie = name + "=" + escape(value) + ";expires="
     + exp.toGMTString()*/
    localStorage.setItem(name, value)
  },
  /**
   * 读取cookies
   */
  getCookie: function (name) {
    /*var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
     if (arr = document.cookie.match(reg)) {
     return unescape(arr[2])
     }
     else {
     return null
     }*/
    var val = localStorage.getItem(name)
    if (val) {
      return val
    } else {
      return null
    }
  },
  /**
   * 删除cookies
   */
  delCookie: function (name) {
    /*var exp = new Date()
     exp.setTime(exp.getTime() - 1000)
     document.cookie = name + "=" + escape('') + ";expires="
     + exp.toGMTString()*/
    localStorage.removeItem(name)
  },
  /**
   * 加密
   */
  compile: function (code) {
    var c = String.fromCharCode(code.charCodeAt(0) + code.length)
    for (var i = 1; i < code.length; i++) {
      c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1))
    }
    return escape(c)
  },
  /**
   * 解密
   */
  uncompile: function (code) {
    code = unescape(code)
    var c = String.fromCharCode(code.charCodeAt(0) - code.length)
    for (var i = 1; i < code.length; i++) {
      c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1))
    }
    return c
  },
  /**
   * 判断元素id是否存在于arr数组中，存在返回true，不存在返回false
   * @param arr
   * @param id
   * @returns {boolean}
   */
  idInArray: function (id, arr) {
    var _this = this
    var len = arr.length
    var total = 0
    for (var i = 0; i < len; i++) {
      if (arr[i].id == id) {
        total = parseInt(total) + 1
        break
      }
    }
    return (parseInt(total) > 0) ? true : false
  },
  inArray: function (val, arr) {
    var _this = this
    var len = arr.length
    var total = 0
    for (var i = 0; i < len; i++) {
      if (arr[i] == val) {
        total = parseInt(total) + 1
        break
      }
    }
    return (parseInt(total) > 0) ? true : false
  },
  // 下载文件
  FileDownloader: function (url, name) {
    new FileDownloader({
      url: encodeURI(url),
      filename: name
    })
  },
  // 下载文件
  DownloadFile: function (url, name) {
    try {
      var DownloadFile_a_id = document.getElementById('DownloadFile_a_id')
      DownloadFile_a_id.href = url
      DownloadFile_a_id.download = name
      DownloadFile_a_id.click()
    } catch (e) {

    }
  },
  // 深复制对象方法
  cloneObj: function (obj) {
    var newObj = {}
    if (obj instanceof Array) {
      newObj = []
    }
    for (var key in obj) {
      var val = obj[key]
      newObj[key] = typeof val === 'object' ? this.cloneObj(val) : val
    }
    return newObj
  },
  // 深复制数组方法
  copyArr: function (arr) {
    let res = []
    for (let i = 0; i < arr.length; i++) {
      res.push(arr[i])
    }
    return res
  },
  // 合并数组并去重
  mergeArray: function (arr2, arr1) {
    for (var i = 0; i < arr1.length; i++) {
      for (var j = 0; j < arr2.length; j++) {
        if (arr1[i] === arr2[j]) {
          arr1.splice(i, 1)
        }
      }
    }
    for (var ii = 0; ii < arr1.length; ii++) {
      arr2.push(arr1[ii])
    }
    return arr2
  },
  // 数组去重
  onlyArray: function (array) {
    var temp = []
    for (var i = 0; i < array.length; i++) {
      if (temp.indexOf(array[i]) <= -1) {
        temp.push(array[i])
      }
    }
    return temp
  },
  // 数组对象去重(以obj中id去重)
  onlyArrayObj: function (arr) {
    var result = [];
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
      if (!obj[arr[i].id]) {
        result.push(arr[i]);
        obj[arr[i].id] = true;
      }
    }
    return result
  },
  // 删除数组中的值
  delArrayVal: function (arr, val) {
    arr = arr ? arr : [];
    // 逆向循环
    for (let i = arr.length - 1; i >= 0; i--) {
      if (arr[i] === val) {
        arr.splice(i, 1);
      }
    }
    return arr;
  },
  // 生成随机数
  generateRandom: function (arr) {
    var temp = []
    var count = arr.length
    for (var i = 0; i < count; i++) {
      var num = Math.floor(Math.random() * arr.length)
      temp.push(arr[num])
      arr.splice(num, 1)
    }
    return temp
  },
  // 获取随机数
  getRandom: function () {
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e']
    var numArr = this.generateRandom(arr)
    var str = ''
    for (var k in numArr) {
      if (!numArr[k]) {
        continue
      }
      var val = numArr[k].toString()
      str += val
    }
    return str
  },
  // 判断是不是数组
  isArrayFn: function (arr) {
    if (typeof Array.isArray === 'function') {
      return Array.isArray(arr)
    } else {
      return Object.prototype.toString.call(arr) === '[object Array]'
    }
  },
  // 判断两个数组是否相等
  toCompareArray: function (arr1, arr2) {
    var _this = this;
    arr1 = _this.isArrayFn(arr1) ? arr1 : [];
    arr2 = _this.isArrayFn(arr2) ? arr2 : [];
    var bool = arr1.sort().toString() == arr2.sort().toString() ? true : false;
    return bool;
  },
  // 判断当前用户是：管理员
  is_administrator: function () {
    var leadership = false
    var departments = this.toJson(localStorage.getItem('userInfo')).departments || []
    for (var k in departments) {
      if (!departments[k]) {
        continue
      }
      var position = departments[k].position || []
      for (var p in position) {
        if (!position[p]) {
          continue
        }
        var pos = [1]
        var id = position[p].id
        if (pos.indexOf(id) > -1) {
          leadership = true
          break
        }
      }
    }
    return leadership
  },
  // 判断当前用户是：正领导、副领导
  is_leadership: function () {
    var leadership = false
    var departments = this.toJson(localStorage.getItem('userInfo')).departments || []
    for (var k in departments) {
      if (!departments[k]) {
        continue
      }
      var position = departments[k].position || []
      for (var p in position) {
        if (!position[p]) {
          continue
        }
        var pos = [2, 3]
        var id = position[p].id
        if (pos.indexOf(id) > -1) {
          leadership = true
          break
        }
      }
    }
    return leadership
  },
  // 消息中心，判断是否有未读的
  localMessage_reading_fun: function (fun) {
    var _this = this;
    var data = {
      uid: Util.toJson(localStorage.getItem('userInfo')).id,
      page: 1,
      size: 10,
    };
    var params = {
      url: '/message-history/list',
      type: Util.method.post,
      data: data,
      success: _successFun
    };
    Util.ajax(_this, params);
    function _successFun(res) {
      fun(res);
    }
  },
  // 更新消息中心未读数
  get_all_reading: function (context) {
    var _this = context;
    var __this = this;
    this.localMessage_reading_fun(function (res) {
      var unread = 0;
      if (res.result == 0) {
        if (res.unread && res.unread > 0) {
          unread = res.unread;
        }
      }
      _this.$store.state.app.localMessage_unread = unread;
    });
  },
  // 收到推送信息
  onCustomSysMsg: function (context, msg) {
    var _this = context;
    var __this = this;
    var content = msg.content;
    var contentObj = Util.toJson(content);

    if (contentObj && contentObj.type && contentObj.type == 'push') {//推送消息
      var pushData = contentObj.data ? contentObj.data : {};
      var from_id = pushData.from_id;
      var from = pushData.from;
      var title = pushData.title;
      var type = pushData.type;
      var content = pushData.content;
      content = content.replace(/,点击查看/g, '');

      var name = new Date().getTime() + '_' + __this.getRandom();

      function onCloseFun(nameid) {
        _this.$Notice.close(nameid);

        sessionStorage.setItem('from_id', from_id);

        switch (from) {
          case 'task' ://任务
            _this.$router.push({
              name: 'task_index'
            });
            break;
          case 'journal' ://日志
            sessionStorage.setItem('journal_title', title);
            sessionStorage.removeItem('from_id');
            _this.$router.push({
              name: 'logs_index'
            });
            break;
          case 'approval' ://审批
            localStorage.setItem('approval_type', 'approving');//待我审批的
            _this.$router.push({
              name: 'approval_index'
            });
            break;
          case 'announcement' :// 公告
            _this.$router.push({
              name: 'affiche_index'
            });
            break;
          case 'meeting' :// 会议
            _this.$router.push({
              name: 'meeting'
            });
            break;
          case 'clock' :// 签到
            sessionStorage.removeItem('from_id');
            _this.$router.push({
              name: 'clock_today'
            });
            break;
          case 'retire' :// 退休
            _this.$router.push({
              name: 'user_retired'
            });
            break;
          case 'email' :// 微邮
            _this.$router.push({
              name: 'email_index'
            });
            break;
          case 'feedback' :// 意见反馈
            _this.$router.push({
              name: 'feedback_add'
            });
            break;
          default :
            sessionStorage.removeItem('from_id');
            break;
        }
        // __this.get_all_reading(_this);
      }

      _this.$Notice.info({
        title: title,
        desc: content,
        duration: 5,
        name: name,//当前通知的唯一标识
        //onClose: onCloseFun,//关闭时回调
        render: h => {
          return h('span', [
            h('div', {
              style: {
                cursor: 'pointer'
              },
              on: {
                click: e => {
                  e.stopPropagation();
                  onCloseFun(name);
                }
              }
            }, content),
          ])
        }
      });
      __this.get_all_reading(_this);
    }
  },
  // 数组中对象，去重
  arrayObjUnique: function (arr, name) {
    var hash = {};
    return arr.reduce(function (item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
      return item;
    }, []);
  },
  // 图片另存为
  downLoadImage: function (imagePathURL) {
    var _this = this;

  },
  // 抽屉页面滚动到顶部
  Drawer2Top: function (context) {
    var _this = this;
    context.$nextTick(function () {
      setTimeout(function () {
        $('.Drawer-body .ivu-drawer-body').animate({scrollTop: '0px'}, 100);
      }, 300);
    });
  },
  // 字符串包含url
  hasUrl: function (str_url) {
    var _this = this;
    var strRegex = "((https|http)?://)"
      + "(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
      + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
      + "|" // 允许IP和DOMAIN（域名）
      + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
      + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
      + "[a-z]{2,6})" // first level domain- .com or .museum
      + "(:[0-9]{1,4})?" // 端口- :80
      + "((/?)|" // a slash isn't required if there is no file name
      + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)";
    var re = new RegExp(strRegex);
    //re.test()
    if (re.test(str_url)) {
      return (true);
    } else {
      return (false);
    }
  },
  // 提取字符串中的url，返回数组
  httpString: function (str_url) {
    var reg = /(https?|http):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
    var url = str_url.match(reg);
    return (url)
  },
  // 获取本地存储数据
  getLocalStorageData: function () {
    var _this = this;
    var Obj = {};
    var str = localStorage.getItem('localStorageData');
    if (str) {
      Obj = _this.toJson(str);
    }
    if (!Obj.chat) { // 消息
      Obj.chat = [];
    }
    if (!Obj.approval) { // 审批
      Obj.approval = [];
    }
    if (!Obj.task) { // 任务
      Obj.task = [];
    }
    if (!Obj.journal) { // 日志
      Obj.journal = [];
    }
    return Obj;
  },
  // 保存本地存储数据
  setLocalStorageData: function (Obj) {
    var _this = this;
    if (Obj) {
      localStorage.setItem('localStorageData', _this.toStr(Obj));
    }
  },
  // 根据type 更新数据,返回新数组
  update2type: function (Arr, type, data) {
    var _this = this;
    var haveType = false;
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var t = Arr[k].type || '';
      if (type == t) { // 存在就更新
        Arr[k].data = data;
        haveType = true;
        break;
      }
    }
    if (haveType == false) { // 不存在就添加
      var obj = {
        type: type,
        id: -1,
        data: data,
      };
      Arr.push(obj);
    }
    return Arr;
  },
  // 根据type,获取数据obj
  getData2type: function (Arr, type) {
    var _this = this;
    var Obj = {};
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var t = Arr[k].type || '';
      if (type == t) { // 存在
        Obj = Arr[k];
        break;
      }
    }
    return Obj;
  },
  // 根据id 更新数据,返回新数组
  update2id: function (Arr, id, data) {
    var _this = this;
    var haveType = false;
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var i = Arr[k].id || '';
      if (id == i) { // 存在就更新
        Arr[k].data = data;
        haveType = true;
        break;
      }
    }
    if (haveType == false) { // 不存在就添加
      var obj = {
        id: id,
        data: data,
      };
      Arr.push(obj);
    }
    return Arr;
  },
  // 根据id,获取数据obj
  getData2id: function (Arr, id) {
    var _this = this;
    var Obj = {};
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var i = Arr[k].id || '';
      if (id == i) { // 存在
        Obj = Arr[k];
        break;
      }
    }
    return Obj;
  },
  // 判断是否为数组的第一个
  isArrayFast: function (arr, id) {
    var _this = this;
    var bool = false;
    if (arr && id && arr.length > 0 && arr[0].id == id) {
      bool = true;
    }
    return bool;
  },
  // 判断是否为数组的最后一个
  isArrayLast: function (arr, id) {
    var _this = this;
    var bool = false;
    if (arr && id && arr.length > 0 && arr[arr.length - 1].id == id) {
      bool = true;
    }
    return bool;
  },
  // 获取上一个
  getArrayUp: function (arr, id) {
    var _this = this;
    var obj = null;
    var key = 0;
    if (arr && id && arr.length > 0) {
      for (var i in arr) {
        if (!arr[i]) {
          continue;
        }
        if (arr[i].id == id) {
          key = parseInt(i);
          break;
        }
      }
      if (key > 0) {
        obj = arr[key - 1];
      }
    }
    return obj;
  },
  // 获取下一个
  getArrayDown: function (arr, id) {
    var _this = this;
    var obj = null;
    if (arr && id && arr.length > 0) {
      var key = arr.length;
      for (var i in arr) {
        if (!arr[i]) {
          continue;
        }
        if (arr[i].id == id) {
          key = parseInt(i);
          break;
        }
      }
      if (key < arr.length - 1) {
        obj = arr[key + 1];
      }
    }
    return obj;
  },
  // 获取url中的参数
  GetQueryString: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    }
    return null;
  },
  // 弹框
  showToast: {
    success: function (_this, str, times = 6) {
      if (!str) {
        return false;
      }
      _this.$Message.destroy();
      _this.$Message.success({
        content: str,
        duration: times
      });
    },
    error: function (_this, str, times = 6) {
      if (!str) {
        return false;
      }
      _this.$Message.destroy();
      _this.$Message.error({
        content: str,
        duration: times
      });
    },
  },

}
export default utils
